import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { getCompany,delCompany,addCompany,updateCompany,listCompanyLogin} from "@/api/modules/company";
import { upload } from "@/api/modules/common";
import { ProFormColumnsType } from '@ant-design/pro-components'


const Company = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [onReloadNum,setOnReloadNum] = useState(null)
  const [visData,setVisData] = useState(false)
  
  const formColumns:ProFormColumnsType[] = [{
    title: t('company.code'),
    dataIndex: 'code',
    valueType: 'text', 
  },{
    title: t('company.companyName'),
    dataIndex: 'companyName',
    valueType: 'text', 
  }]

  const columns: any = [
    {
      title: t('company.code'),
      dataIndex: 'code',
      key: 'code',
      fixed:'left',
    },
    {
      title: t('company.companyName'),
      dataIndex: 'companyName',
      key: 'companyName',
    },
    {
      title: t('company.companyAddress'),
      dataIndex: 'companyAddress',
      key: 'companyAddress',
    },
    {
      title: t('company.evaluationCompany'),
      dataIndex: 'evaluationCompany',
      key: 'evaluationCompany',
    },
    {
      title: t('company.evaluator'),
      dataIndex: 'evaluator',
      key: 'evaluator',
    },
    {
      title: t('company.sysName'),
      dataIndex: 'sysName',
      key: 'sysName',
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          <Button type="link" onClick={() => handleEdit(record)}>  
          {t('edit')}  
          </Button>  
         {/* 使用三元运算符来判断显示哪个按钮 */}  
         {record.status === 'Invisible' ? (  
            <Button type="link" danger onClick={() => handleRecover(record.id)}>  
              {t('recover')}  
            </Button>  
          ) : (  
            <Button type="link" danger onClick={() => handleDelete(record.id)}>  
              {t('delete')}  
            </Button>  
          )} 
   
        </>  
      ),  
    },  
  ];

  const showAllData = () =>{
    setVisData(true)
    setOnReloadNum(Date.now())
  }

  const showNoAllData = () =>{
    setVisData(false)
    setOnReloadNum(Date.now())
  }

  const getData = async (formData) => {
    if(visData==false){
      const { success, data} = await listCompanyLogin({...formData, orderby: 'id', order: 0,status:'default'})
      if(!success) return false
      console.log(data)
      const list = data.rows
      return {
        data: list,
        total: data.total
      }
    }else{
      const { success, data} = await listCompanyLogin({...formData, orderby: 'id', order: 0,status:''})
      if(!success) return false
      console.log(data)
      const list = data.rows
      return {
        data: list,
        total: data.total
      }
    }

  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    if(Title=='新增/New'){
        //新增
        values.id =null
        addCompany(values).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        updateCompany(values).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView = (record) =>{
   SetisView(true)
   setTitle("查看/View")
   console.log(record,'record')
   form.setFieldsValue({ ...record });  
   setIsModalVisible(true);  
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    const form = {id:key,status:'Invisible'}
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        updateCompany(form).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
        }) 
      },  
    }); 
  }

  const handleRecover = (key) =>{
    const form = {id:key,status:''}
    updateCompany(form).then(res=>{
      message.success("Success")
      setOnReloadNum(Date.now())
  }) 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const renderOperator = <>
    <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
    <Button style={{marginLeft:'1%'}} type="primary"  size="small" onClick={showAllData}>{t('allData')}</Button>
    <Button style={{marginLeft:'1%'}} type="primary"  size="small" onClick={showNoAllData}>{t('nonInvisibleData')}</Button>
  </>
  
  return (
    <div> 
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="code"  
              label={t('company.code')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="companyName"  
              label={t('company.companyName')}  
              rules={[{ required: true, message: '请输入名称！' }]}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="companyAddress"  
              label={t('company.companyAddress')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="evaluationCompany"  
              label={t('company.evaluationCompany')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="evaluator"  
              label={t('company.evaluator')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="sysName"  
              label={t('company.sysName')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
          </Form>  
        </Modal>  
    </div>
  )
}
export default Company
